﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;

namespace ImgUpload
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(opt =>
            {
                string[] urls = Configuration.GetSection("AllowedCores").Value.Split(',');
                opt.AddPolicy("AllowAllOrigin", builder =>
                {
                    builder.WithOrigins(urls);
                    builder.AllowAnyMethod();
                    builder.AllowAnyHeader();
                    builder.AllowCredentials();
                });
            });
            services.AddSingleton<ImageService>();//图片服务
            services.AddSingleton<AliyunService>();//云图片服务
            services.AddOptions().Configure<ConfigDto>(Configuration.GetSection("AppConfig"));
            services.AddOptions().Configure<OssOption>(Configuration.GetSection("OssConfig"));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //使用跨域
            app.UseCors("AllowAllOrigin");
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                //FileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()),
                //设置不限制content-type 该设置可以下载所有类型的文件，但是不建议这么设置，因为不安全
                //下面设置可以下载apk和nupkg类型的文件
                ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
                {
                      { ".apk", "application/vnd.android.package-archive" }
                })
            });

            app.Map("/api/upload", build =>
            {
                build.UseMvc();
            });

            app.Use( async (context, next) =>
            {
                context.Request.Path= context.Request.Path.ToString().Replace("//", "/");
                await next.Invoke();
            });
            app.UseMvc();
        }
    }
}
